<template>
  <div class="schedule-status-management">
    <div class="page-header">
      <h2>排期状态管理</h2>
      <p class="subtitle">管理您的设备上的广告排期状态</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="排期状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 180px">
            <el-option label="待执行" value="PENDING" />
            <el-option label="执行中" value="RUNNING" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="设备">
          <el-select v-model="searchForm.deviceId" placeholder="选择设备" clearable style="width: 180px">
            <el-option 
              v-for="device in deviceList" 
              :key="device.id" 
              :label="device.name" 
              :value="device.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchSchedules">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 排期表格 -->
    <el-card shadow="never" class="table-card">
      <div class="table-operations">
        <span class="table-title">排期列表</span>
        <el-button type="primary" @click="refreshTable">刷新</el-button>
      </div>
      
      <el-table
        v-loading="loading"
        :data="scheduleList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="排期ID" width="80" />
        <el-table-column label="广告信息" min-width="200">
          <template #default="scope">
            <div class="ad-info">
              <span class="ad-name">{{ scope.row.advertisementName }}</span>
              <span class="ad-advertiser">广告主: {{ scope.row.advertiserName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="设备" prop="deviceName" width="150" />
        
        <el-table-column label="排期时间" width="160">
          <template #default="scope">
            <div>{{ formatDate(scope.row.startTime) }}</div>
            <div>至</div>
            <div>{{ formatDate(scope.row.endTime) }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="展示/点击" width="120">
          <template #default="scope">
            <div>展示: {{ scope.row.impressions || 0 }}</div>
            <div>点击: {{ scope.row.clicks || 0 }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <div class="action-buttons">
              <!-- 查看详情 -->
              <el-button 
                type="primary" 
                link 
                size="small" 
                @click="viewScheduleDetail(scope.row)"
              >
                详情
              </el-button>
              
              <!-- 根据当前状态显示可用的状态转换操作 -->
              <el-dropdown 
                v-if="scope.row.status !== 'COMPLETED' && scope.row.status !== 'CANCELLED'"
                trigger="click" 
                @command="(cmd) => handleStatusChange(cmd, scope.row)"
              >
                <el-button type="success" link size="small">
                  状态变更<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item 
                      v-if="scope.row.status === 'PENDING'" 
                      command="RUNNING"
                    >
                      开始执行
                    </el-dropdown-item>
                    <el-dropdown-item 
                      v-if="scope.row.status === 'RUNNING'" 
                      command="COMPLETED"
                    >
                      标记完成
                    </el-dropdown-item>
                    <el-dropdown-item 
                      v-if="scope.row.status === 'PENDING' || scope.row.status === 'RUNNING'" 
                      command="CANCELLED"
                    >
                      取消排期
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :layout="'total, sizes, prev, pager, next'"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 取消排期对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消排期"
      width="500px"
    >
      <el-form :model="cancelForm" :rules="cancelRules" ref="cancelFormRef" label-width="80px">
        <el-form-item label="取消原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入取消排期的原因..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancelSchedule">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 排期详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="排期详情"
      width="700px"
    >
      <el-descriptions v-if="currentSchedule" :column="2" border>
        <el-descriptions-item label="排期ID" :span="2">{{ currentSchedule.id }}</el-descriptions-item>
        <el-descriptions-item label="广告名称" :span="2">{{ currentSchedule.advertisementTitle }}</el-descriptions-item>
        <el-descriptions-item label="广告主">{{ currentSchedule.advertiserName }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ currentSchedule.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ formatDateTime(currentSchedule.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ formatDateTime(currentSchedule.endTime) }}</el-descriptions-item>
        
        <el-descriptions-item label="播放时段" :span="2">
          <div v-if="currentSchedule.timeSlots && currentSchedule.timeSlots.length > 0">
            <div v-for="(slot, index) in currentSchedule.timeSlots" :key="index" class="time-slot">
              {{ slot.startTime }} - {{ slot.endTime }}
            </div>
          </div>
          <div v-else>全天播放</div>
        </el-descriptions-item>
        
        <el-descriptions-item label="状态" :span="2">
          <el-tag :type="getStatusType(currentSchedule.status)">
            {{ getStatusText(currentSchedule.status) }}
          </el-tag>
        </el-descriptions-item>
        
        <el-descriptions-item label="展示次数">{{ currentSchedule.impressions || 0 }}</el-descriptions-item>
        <el-descriptions-item label="点击次数">{{ currentSchedule.clicks || 0 }}</el-descriptions-item>
        
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentSchedule.createdTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(currentSchedule.updatedTime) }}</el-descriptions-item>
        
        <el-descriptions-item label="备注" :span="2">
          {{ currentSchedule.remark || '无' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import { 
  getScheduleList, 
  getScheduleDetail,
  updateScheduleStatus,
  cancelSchedule
} from '@/api/schedule';
import { getDeviceList } from '@/api/device';

const router = useRouter();

// 状态变量
const loading = ref(false);
const scheduleList = ref([]);
const deviceList = ref([]);
const currentSchedule = ref(null);
const cancelDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const cancelFormRef = ref(null);

// 搜索表单
const searchForm = reactive({
  status: '',
  deviceId: '',
  timeRange: [],
});

// 取消表单
const cancelForm = reactive({
  reason: '',
  scheduleId: null
});

// 取消表单验证规则
const cancelRules = {
  reason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 初始化数据
onMounted(() => {
  fetchScheduleList();
  fetchDeviceList();
});

// 获取排期列表
const fetchScheduleList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      status: searchForm.status || null,
      deviceId: searchForm.deviceId || null,
      startDate: searchForm.timeRange && searchForm.timeRange[0] ? searchForm.timeRange[0] : null,
      endDate: searchForm.timeRange && searchForm.timeRange[1] ? searchForm.timeRange[1] : null
    };
    
    const res = await getScheduleList(params);
    console.log(res);
    if (res.data.code === 200) {
      scheduleList.value = res.data.data.records || [];
      pagination.total = res.data.data.total || 0;
    } else {
      ElMessage.error(res.data.message || '获取排期列表失败');
    }
  } catch (error) {
    console.error('获取排期列表异常:', error);
    ElMessage.error('获取排期列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取设备列表
const fetchDeviceList = async () => {
  try {
    const res = await getDeviceList({
      pageNum: 1,
      pageSize: 100,
      onlyOwned: true // 只获取自己的设备
    });
    if (res.data.code === 200) {
      deviceList.value = res.data.data.records || [];
    }
  } catch (error) {
    console.error('获取设备列表异常:', error);
  }
};

// 搜索排期
const searchSchedules = () => {
  pagination.current = 1;
  fetchScheduleList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.status = '';
  searchForm.deviceId = '';
  searchForm.timeRange = [];
  searchSchedules();
};

// 刷新表格
const refreshTable = () => {
  fetchScheduleList();
};

// 查看排期详情
const viewScheduleDetail = async (schedule) => {
  try {
    const res = await getScheduleDetail(schedule.id);
    console.info('查看排期详情:', res);
    if (res.data.code === 200) {
      currentSchedule.value = res.data.data;
      detailDialogVisible.value = true;
    } else {
      ElMessage.error(res.data.message || '获取排期详情失败');
    }
  } catch (error) {
    console.error('获取排期详情异常:', error);
    ElMessage.error('获取排期详情失败');
  }
};

// 处理状态变更
const handleStatusChange = (status, schedule) => {
  if (status === 'CANCELLED') {
    // 显示取消对话框
    cancelForm.scheduleId = schedule.id;
    cancelDialogVisible.value = true;
  } else {
    // 直接确认其他状态变更
    ElMessageBox.confirm(
      `确定要将排期状态更改为"${getStatusText(status)}"吗？`,
      '状态变更确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        const res = await updateScheduleStatus(schedule.id, { status });
        if (res.data.code === 200) {
          ElMessage.success('状态更新成功');
          fetchScheduleList(); // 刷新列表
        } else {
          ElMessage.error(res.data.message || '状态更新失败');
        }
      } catch (error) {
        console.error('状态更新异常:', error);
        ElMessage.error('状态更新失败');
      }
    }).catch(() => {});
  }
};

// 确认取消排期
const confirmCancelSchedule = async () => {
  if (!cancelFormRef.value) return;
  
  try {
    await cancelFormRef.value.validate();
    
    const res = await cancelSchedule(cancelForm.scheduleId);
    
    if (res.data.code === 200) {
      ElMessage.success('排期已取消');
      cancelDialogVisible.value = false;
      fetchScheduleList(); // 刷新列表
    } else {
      ElMessage.error(res.data.message || '取消排期失败');
    }
  } catch (error) {
    console.error('取消排期异常:', error);
    ElMessage.error('取消排期失败: ' + (error.message || '未知错误'));
  }
};

// 处理分页大小变更
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchScheduleList();
};

// 处理分页页码变更
const handleCurrentChange = (page) => {
  pagination.current = page;
  fetchScheduleList();
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'PENDING': return 'warning';
    case 'RUNNING': return 'primary';
    case 'COMPLETED': return 'success';
    case 'CANCELLED': return 'danger';
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'PENDING': return '待执行';
    case 'RUNNING': return '执行中';
    case 'COMPLETED': return '已完成';
    case 'CANCELLED': return '已取消';
    default: return '未知';
  }
};

// 格式化日期
const formatDate = (dateTime) => {
  if (!dateTime) return '未知';
  const date = new Date(dateTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知';
  const date = new Date(dateTime);
  return date.toLocaleString();
};
</script>

<style scoped>
.schedule-status-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.ad-info {
  display: flex;
  flex-direction: column;
}

.ad-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.ad-advertiser {
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.time-slot {
  margin-bottom: 5px;
  display: inline-block;
  margin-right: 15px;
  border: 1px solid #EBEEF5;
  padding: 2px 8px;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
}
</style>